package com.lemon.smartsafety.ui.activity.fire.item.inspection;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingCheckItemRefreshEvent;
import com.lemon.smartsafety.entity.event.datacoll.BuildingPositionRefreshEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.main.OptionItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingBaseCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingItemCountVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.SafeDataServices;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.safe.data.BuildingBaseCheckItemListActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.data.CycleUnitAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class FireInspectionBuildItemAddActivity extends PhotoSelectBaseActivity {
    @Bind(R.id.tv_position_title)
    TextView tvPositionTitle;
    @Bind(R.id.metCheckItemName)
    MaterialEditText metCheckItemName;
    @Bind(R.id.rowCheckItemPick)
    TableRow rowCheckItemPick;
    @Bind(R.id.metCheckCycleValue)
    MaterialEditText  metCheckCycleValue;
    @Bind(R.id.metCheckCycleUnit)
    MaterialEditText  metCheckCycleUnit;
    @Bind(R.id.rowCheckCycleUnit)
    TableRow          rowCheckCycleUnit;
    @Bind(R.id.metRemark)
    MaterialEditText  metRemark;
    @Bind(R.id.mSelectRecycleView)
    RecyclerView mSelectRecycleView;
    @Bind(R.id.chkIsWeibao)
    AppCompatCheckBox chkIsWeibao;
    @Bind(R.id.chkIsPatrol)
    AppCompatCheckBox chkIsPatrol;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.mainContainer)
    LinearLayout mainContainer;


    /**
     * bundle info
     */
    private CompanyBuildingVo mCompanyBuildingVo;
    private CompanyBuildingIndexVo mCompanyBuildingIndexVo;
    private CompanyBuildingItemCountVo mCompanyBuildingItemCountVo;


    private CompanyBuildingBaseCheckItemVo mCheckItem;
    /**
     * 周期
     */
    private OptionItemVo cycleVo;

    private List<OptionItemVo> cycleItems = new ArrayList<>();


    private boolean isEdit = false;




    private MaterialDialog.Builder mMaterialDialog;

    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.build_check_item_title);

    }


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_ITEM_COUNT);

        }


    }


    @Override
    protected void initViews() {
        super.initViews();
        metCheckItemName.setTag("");

        if (null == mCompanyBuildingVo || null == mCompanyBuildingIndexVo || null == mCompanyBuildingItemCountVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
            return;
        }

        initViewValue();


    }

    private void initViewValue() {
        tvPositionTitle.setText(DataInfo.getPositionTitle(mCompanyBuildingVo, mCompanyBuildingIndexVo, mCompanyBuildingItemCountVo));
    }

    /**
     * 初始化这个编辑视图的值
     *
     * @param vo
     */
    private void initEditView(CompanyBuildingCheckItemVo vo) {
        //初始化项目对象
        mCheckItem = new CompanyBuildingBaseCheckItemVo();
        mCheckItem.setObjectId(vo.getObjectId());
        mCheckItem.setObjectTitle(vo.getObjectTitle());
        mCheckItem.setObjectId(vo.getObjectId());
        mCheckItem.setObjectTitle(vo.getObjectTitle());
        mCheckItem.setBuildingTypeCode(vo.getBuildingTypeCode());
        mCheckItem.setBuildingTypeName(vo.getBuildingTypeName());
        mCheckItem.setPlaceTypeId(vo.getPlaceTypeId());
        mCheckItem.setPlaceTypeName(vo.getPlaceTypeName());
        mCheckItem.setRelationFireSystem(vo.getRelationFireSystem());
        mCheckItem.setRelationFireSystemName(vo.getRelationFireSystemName());
        mCheckItem.setCheckValidity(vo.getCheckValidity());
        mCheckItem.setUnitCode(vo.getUnitCode());

        metCheckItemName.setText(StringUtils.nullValue(mCheckItem.getObjectTitle()));
        metCheckItemName.setTag(StringUtils.nullValue(mCheckItem.getObjectId()));


        //初始化周期
        metCheckCycleValue.setText(StringUtils.nullValue(vo.getCheckValidity()));
        cycleVo = new OptionItemVo();
        cycleVo.setVoId(StringUtils.nullValue(vo.getUnitCode()));
        cycleVo.setTitle(DataInfo.getUnitName(vo.getUnitCode()));
        metCheckCycleUnit.setText(StringUtils.nullValue(vo.getUnitName()));


        chkIsWeibao.setChecked(StringUtils.getBoolean(vo.getIsKeepCheck()));
        chkIsPatrol.setChecked(StringUtils.getBoolean(vo.getIsPatrol()));


        metRemark.setText(StringUtils.nullValue(vo.getRemark()));

        addPlayViewItems(vo.getPlayViewList());
    }


    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(FireInspectionBuildItemAddActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_inspection_build_item_add;
    }


//    /**
//     * 显示选择照片的界面
//     */
//    public void showSelectPhoto() {
//        showSelectPhotoView();
//    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        mCheckItem = (CompanyBuildingBaseCheckItemVo) event.getData();
        metCheckItemName.setText(StringUtils.nullValue(mCheckItem.getObjectTitle()));
        metCheckItemName.setTag(StringUtils.nullValue(mCheckItem.getObjectId()));

        //这里处理带回来的周期数据
        if (cycleVo == null) {
            cycleVo = new OptionItemVo();
        }
        cycleVo.setVoId(StringUtils.nullValue(mCheckItem.getUnitCode()));
        cycleVo.setTitle(DataInfo.getUnitName(mCheckItem.getUnitCode()));


        metCheckCycleValue.setText(StringUtils.nullValue(mCheckItem.getCheckValidity()));

        metCheckCycleUnit.setText(StringUtils.nullValue(cycleVo.getTitle()));

        if (mCheckItem.getIsKeepCheck() != null && mCheckItem.getIsKeepCheck().equals("1")) {
            chkIsWeibao.setChecked(true);
        } else {
            chkIsWeibao.setChecked(false);
        }

    }

    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        if (StringUtils.nullValue(metCheckItemName.getText().toString().trim()).length() == 0) {
            mHUDUtil.showErrorTip(getString(R.string.build_check_item_prop_error_select_item));
            metCheckItemName.setError(getString(R.string.build_check_item_prop_error_select_item));
            return false;
        }


        if (StringUtils.nullValue(metCheckCycleValue.getText().toString().trim()).length() == 0) {
            mHUDUtil.showErrorTip(getString(R.string.build_check_item_prop_error_cycle_value));
            metCheckCycleValue.setError(getString(R.string.build_check_item_prop_error_cycle_value));
            return false;
        }

        if (StringUtils.nullValue(metCheckCycleUnit.getText().toString().trim()).length() == 0) {
            mHUDUtil.showErrorTip(getString(R.string.build_check_item_prop_error_cycle_unit));
            metCheckCycleUnit.setError(getString(R.string.build_check_item_prop_error_cycle_unit));
            return false;
        }

        return true;

    }

    @OnClick({R.id.rowCheckItemPick, R.id.metCheckItemName})
    protected void baseCheckItemSelect() {
        Bundle bundle = new Bundle();
        if (null != mCheckItem) {
            bundle.putString(BundleKey.OLD_SELECT_VALUE, mCheckItem.getObjectId());
        }
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        UIHelper.showActivity(FireInspectionBuildItemAddActivity.this, bundle, BuildingBaseCheckItemListActivity.class);
    }

    @OnClick({R.id.rowCheckCycleUnit, R.id.metCheckCycleUnit})
    protected void checkCycle() {
        if (cycleItems != null && cycleItems.size() != 0) {
            showCycleDialog(cycleItems);
        } else {
            SafeDataServices.init().getCheckCycle();
        }
    }


    private void showCycleDialog(List<OptionItemVo> items) {
        new MaterialDialog.Builder(this).title(R.string.build_check_item_prop_item_cycle_unit).adapter(new CycleUnitAdapter(items), new MaterialDialog.ListCallback() {
            @Override
            public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                cycleVo = cycleItems.get(which);
                metCheckCycleUnit.setText(cycleVo.getTitle());
                dialog.dismiss();
            }
        }).show();
    }


    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }

        mMaterialDialog = getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        });
        mMaterialDialog.show();

    }


    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("company_building_item", "item_id", "");
        params.put("_txtIdNumeric", "0");

        params.put("handler", "com.lemon.fire_control.CompanyBuildingItemAction");
        params.put("op", "new_company_building_item");



        params.put("item_id", "");
        params.put("txtObjectId", metCheckItemName.getTag().toString(), Field.TYPE_INT);
        params.put("txtObjectTitle", metCheckItemName.getText().toString().trim(), Field.TYPE_STRING);
        //类型暂时去掉
        //params.put("txtItemTypeCode", typeVo.getVoId(), Field.TYPE_STRING);
        params.put("txtRelationFireSystem", mCheckItem.getRelationFireSystem(), Field.TYPE_STRING);
        params.put("txtPlaceTypeId", mCheckItem.getPlaceTypeId(), Field.TYPE_INT);
        params.put("txtCheckValidity", metCheckCycleValue.getText().toString().trim(), Field.TYPE_INT);
        params.put("txtUnitCode", cycleVo.getVoId(), Field.TYPE_STRING);
        params.put("txtRemark", metRemark.getText().toString().trim(), Field.TYPE_STRING);
        params.put("chkIsKeepCheck", chkIsWeibao.isChecked() ? "1" : "0", Field.TYPE_INT);
        params.put("chkIsPatrol", chkIsPatrol.isChecked() ? "1" : "0", Field.TYPE_INT);
        params.put("txtFloorNumber", mCompanyBuildingItemCountVo.getFloorNumber(), Field.TYPE_INT);
        params.put("txtPositionMark", mCompanyBuildingItemCountVo.getPositionMark(), Field.TYPE_INT);
        params.put("txtBuildingId", mCompanyBuildingIndexVo.getBuildingId(), Field.TYPE_STRING);
        params.put("_txtDataSourceProvider", "com.lemon.fire_control.SafeConnProvider");
        params.put("_no_html", "1");



        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(List<UploadFileItem> data) {
                if (data != null && data.size() != 0) {
                    params.put("files", mGson.toJson(data));
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        //  SafeDataServices.init().saveCheckItemInfoAction(params, isEdit);
                        initCompanySave(params);
                    }
                });
            }
        });
    }



    /**
     * 保存
     */
    public void initCompanySave(LemonRequestParams params) {
     /*   SharedPreferencesServer mSharedPreferencesServer=new SharedPreferencesServer(IApplication.context());
        String serverUrl = mSharedPreferencesServer.getRequestUrl( UrlInfo.BIND_COMPANY_EDIT_ACTION );
        LogUtils.LOGE("serverUrl:"+serverUrl);*/

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.ActionServlet), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            ToastUtils.toastMsg(baseMode.getMsg());

                            AppService.getBus().post(new RefreshViewEntity(FireInspectionBuildItemAddActivity.class.getName()));
                            callFinish();
                        } else {
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }

                }
            }
        });

    }





    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_CYCLE == event.getTag()) {//周期单位
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    cycleItems.clear();
                    cycleItems.addAll((Collection<? extends OptionItemVo>) event.getObj());
                    showCycleDialog(cycleItems);
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if (EventTag.TAG_SAFE_DATA_COLLECTION_BUILDING_CHECK_ITEM_SAVE_ACTION == event.getTag()) {//检查项目Action
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            if (!isEdit) {
                                BuildingPositionRefreshEvent refreshEvent = new BuildingPositionRefreshEvent();
                                refreshEvent.setTag(BuildingPositionRefreshEvent.class.getName());
                                AppService.getBus().post(refreshEvent);
                            }else{
                                BuildingCheckItemRefreshEvent itemRefreshEvent = new BuildingCheckItemRefreshEvent();
                                itemRefreshEvent.setTag(BuildingCheckItemRefreshEvent.class.getName());
                                AppService.getBus().post(itemRefreshEvent);
                            }
                            AppManager.getAppManager().finishActivity(FireInspectionBuildItemAddActivity.this);

                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        BuildingPositionRefreshEvent event = new BuildingPositionRefreshEvent();
        event.setTag(BuildingPositionRefreshEvent.class.getName());
        AppService.getBus().post(event);

    }
}
